package com.module.imagelib.glide.transfor;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.util.Util;

import java.nio.ByteBuffer;
import java.security.MessageDigest;

import androidx.annotation.Nullable;

/**
 * 矩形或圆角
 * Created by dell on 2017/10/25
 */

public class GlideRoundTransform extends BitmapTransformation {

    float mRadius = 0f;
    protected int mBorderWidth = 0;
    protected int mBorderColor = Color.parseColor("#000000");
    private static String ID = "com.kangcun.imageloader.glide.transfor.GlideRoundTransform";
    private static final byte[] ID_BYTES = ID.getBytes(CHARSET);

    public GlideRoundTransform() {
    }

    public GlideRoundTransform(int width, String color) {
        this.mBorderWidth = width;
        this.mBorderColor = Color.parseColor(color);
    }

    public GlideRoundTransform(int dp) {
        this.mRadius = Resources.getSystem().getDisplayMetrics().density * dp;
    }

    public GlideRoundTransform(int dp, int width, String color) {
        this(dp);
        this.mBorderWidth = width;
        this.mBorderColor = Color.parseColor(color);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform, outWidth, outHeight);
    }

    private Bitmap roundCrop(BitmapPool pool, Bitmap source, int outWidth, int outHeight) {
        if (source == null) return null;
//        int width = source.getWidth();
//        int height = source.getHeight();
//        int x=0;
//        int y=0;
//        if(width>height){
//            //宽大于高 计算原图中心点X与目标图中心X的距离
//            x = (width / 2) - (outWidth / 2);
//        }else if(width<height){
//            //高大于宽 计算原图中心点Y与目标图中心Y的距离
//            y = (height / 2) - (outHeight / 2);
//        }
        //显示图片中心 同上
        int x = (source.getWidth() - outWidth) / 2;
        int y = (source.getHeight() - outHeight) / 2;
        //原图转成指定宽高矩形切割图
        Bitmap newSource = Bitmap.createBitmap(source, x, y, outWidth, outHeight);
        //创建空的bitmap
        Bitmap result = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);
        }
        //创建画布
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        //矩形图配合圆角图形生成圆角图
        paint.setShader(new BitmapShader(newSource, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0f, 0f, newSource.getWidth(), newSource.getHeight());

        int sr = 0;
        //缩小canvas，避免边框遮盖合成图片
        if (mBorderWidth > 0) {
            sr = canvas.saveLayer(rectF, null, Canvas.ALL_SAVE_FLAG);
            float sx = 1.0f * (rectF.width() - 2 * mBorderWidth) / rectF.width();
            float sy = 1.0f * (rectF.height() - 2 * mBorderWidth) / rectF.height();
            canvas.scale(sx, sy, rectF.width() / 2, rectF.height() / 2);
        }
        //原图
        if (mRadius > 0) {
            canvas.drawRoundRect(rectF, mRadius, mRadius, paint);
        } else {
            canvas.drawRect(rectF, paint);
        }

        //画边框
        if (mBorderWidth > 0) {
            //恢复画布
            canvas.restoreToCount(sr);
            RectF borderRectF = new RectF(mBorderWidth / 2.0f, mBorderWidth / 2.0f, rectF.width() - mBorderWidth / 2.0f, rectF.height() - mBorderWidth / 2.0f);
            drawBorder(canvas, borderRectF);
        }

        return result;
    }

    /**
     * 必须加-防止闪烁
     * @param messageDigest
     */
    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {
        messageDigest.update(ID_BYTES);
        byte[] radiusData = ByteBuffer.allocate(4).putFloat(mRadius).array();
        messageDigest.update(radiusData);
    }

    /**
     * 必须加-防止闪烁
     * @param obj
     */
    @Override
    public boolean equals(@Nullable Object obj) {
        if (obj instanceof GlideRoundTransform) {
            GlideRoundTransform other = (GlideRoundTransform) obj;
            return mRadius == other.mRadius;
        }
        return false;
    }

    /**
     * 必须加-防止闪烁
     */
    @Override
    public int hashCode() {
        return Util.hashCode(ID.hashCode(),
                Util.hashCode(mRadius));
    }

    public void drawBorder(Canvas canvas, RectF borderRectF) {
        Path mPath = new Path();
        Paint mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(mBorderColor);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mBorderWidth);
        float radius = mRadius + mBorderWidth / 2.0f;
        float[] radiusArray = {radius, radius, radius, radius, radius, radius, radius, radius};
        if (mRadius > 0) {
            mPath.addRoundRect(borderRectF, radiusArray, Path.Direction.CW);
        } else {
            mPath.addRect(borderRectF, Path.Direction.CW);
        }
        canvas.drawPath(mPath, mPaint);
    }


}